angular.module('bw.services')
    .factory('httpInterceptor', ['$q', '$injector', function($q, $injector) {
        return {
            'request': function(config) {
                if (config.isLoading !== false) config.loadingId = $injector.get("toast").showLoading();
                extendHeaders(config);
                return config;
            },
            'requestError': function(rejection) {
                if (rejection.config.isLoading !== false) $injector.get("toast").hideLoading(rejection.config.loadingId);
                return $q.reject(rejection);
            },
            'response': function(response) {
                if (response.config.isLoading !== false) $injector.get("toast").hideLoading(response.config.loadingId);
                return response || $q.when(response);
            },
            'responseError': function(rejection) {
                if (rejection.config.isLoading !== false) $injector.get("toast").hideLoading(rejection.config.loadingId);
                return $q.reject(rejection);
            }
        };

        /** 
         *config: 请求配置信息
         */
        function extendHeaders(config) {
            config.headers = config.headers || {};
            var Authorization = localStorage.getItem("_token") ? JSON.parse(localStorage.getItem("_token")) : null;
            config.headers['Authorization'] = "Bearer " + Authorization;
        };

    }]);
